package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${ruije.path}")
    private String basepath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());
        String filename=file.getOriginalFilename();
        String t=filename.substring(filename.lastIndexOf("."));
        String name= String.valueOf(UUID.randomUUID())+t;

        File fl=new File(basepath);
        if (!fl.exists()){
            fl.mkdirs();
        }
        try {
            file.transferTo(new File(basepath+name));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(name);
    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            //创建输入流
            FileInputStream fileInputStream=new FileInputStream(new File(basepath+name));

            //创建输出流
            ServletOutputStream servletOutputStream=response.getOutputStream();

            int len=0;
            byte[] bf=new byte[1024];

            while ((len=fileInputStream.read(bf))!=-1){
                servletOutputStream.write(bf,0,len);
                servletOutputStream.flush();
            }

            //关闭资源
            fileInputStream.close();
            servletOutputStream.close();
            } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }



}
